﻿using System;
using System.Xml;
using System.Text.RegularExpressions;
using Kwan.Cache;

namespace Kwan.Helper.Xmls
{
    public class XmlHelper:IDisposable
    {
        #region 范例
        //string xml = Server.MapPath("XmlFile.xml");
        //插入元素
        //XmlHelper.Insert(xml, "/Root", "Studio", "", "");
        //插入元素/属性
        //XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "小路工作室");
        //XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "丁香鱼工作室");
        //XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "谱天城工作室");
        //XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "Master", "", "红尘静思");
        //插入属性
        //XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='小路工作室']", "", "Url", "http://www.wzlu.com/");
        //XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='丁香鱼工作室']", "", "Url", "http://www.luckfish.net/");
        //XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "", "Url", "http://www.putiancheng.com/");
        //修改元素值
        //XmlHelper.Update(xml, "/Root/Studio/Site[@Name='谱天城工作室']/Master", "", "RedDust");
        //修改属性值
        //XmlHelper.Update(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "Url", "http://www.putiancheng.net/");
        //XmlHelper.Update(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "Name", "PuTianCheng Studio");
        //读取元素值
        //Response.Write("<div>" + XmlHelper.Read(xml, "/Root/Studio/Site/Master", "") + "</div>");
        //读取属性值
        //Response.Write("<div>" + XmlHelper.Read(xml, "/Root/Studio/Site", "Url") + "</div>");
        //读取特定属性值
        //Response.Write("<div>" + XmlHelper.Read(xml, "/Root/Studio/Site[@Name='丁香鱼工作室']", "Url") + "</div>");
        //删除属性
        //XmlHelper.Delete(xml, "/Root/Studio/Site[@Name='小路工作室']", "Url");
        //删除元素
        //XmlHelper.Delete(xml, "/Root/Studio", "");
        #endregion

        public XmlDocument xmlDoc;//xml对象
        protected CacheManage theCache;//缓存对象
        public string xmlFilePath = string.Empty;
        public string xmlCacheKey = string.Empty;

        public XmlHelper(string path)
        {
            theCache = CacheManage.Instance;
            InitXmlDoc(path);
        }

        #region 读取数据
        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="attribute">属性名，非空时返回该属性值，否则返回串联值</param>
        /// <returns>string</returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.Read(path, "/Node", "")
         * XmlHelper.Read(path, "/Node/Element[@Attribute='Name']", "Attribute")
         ************************************************/
        public string Read(string node, string attribute)
        {
            string value = "";
            try
            {
                XmlNode xn = xmlDoc.SelectSingleNode(node);
                value = (attribute.Equals("") ? xn.InnerText : xn.Attributes[attribute].Value);
            }
            catch { value = null; }
            return value;
        }
        public void InitXmlDoc(string path)
        {
            if (xmlDoc == null)
            {
                this.xmlCacheKey = GenerateKey(path);
                LoadFromCache();
            }
        }
        public void LoadFromCache()
        {
            if (theCache.Contains(this.xmlCacheKey))//缓存中存在对应值是key的对象
            {
                xmlDoc = theCache.Get(this.xmlCacheKey) as XmlDocument;
            }
            else
            {
                xmlDoc = LoadFromFile(this.xmlFilePath);
                theCache.Add(this.xmlCacheKey, xmlDoc, xmlFilePath, 30);
            }
        }
        private XmlDocument LoadFromFile(string path)
        {
            XmlDocument newDoc = new XmlDocument();
            newDoc.Load(path);
            return newDoc;
        }
        private string GenerateKey(string absFilePath)
        {
            xmlFilePath = absFilePath;
            absFilePath = absFilePath.Replace(":", "").Replace("/", "").Replace("\\", "").Replace(".", "");
            return absFilePath;
        }
        public void Save()
        {
            xmlDoc.Save(xmlFilePath);
            theCache.SetChange(xmlCacheKey, true);
        }
        #endregion

        #region 插入数据
        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="element">元素名，非空时插入新元素，否则在该元素中插入属性</param>
        /// <param name="attribute">属性名，非空时插入该元素属性值，否则插入元素值</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.Insert(path, "/Node", "Element", "", "Value")
         * XmlHelper.Insert(path, "/Node", "Element", "Attribute", "Value")
         * XmlHelper.Insert(path, "/Node", "", "Attribute", "Value")
         ************************************************/
        public void Insert(string node, string element, string attribute, string value)
        {
            try
            {
                XmlNode xn = xmlDoc.SelectSingleNode(node);
                //if (Read(path, node + "/" + element, "") != null) return;
                if (element.Equals(""))
                {
                    if (!attribute.Equals(""))
                    {
                        XmlElement xe = (XmlElement)xn;
                        xe.SetAttribute(attribute, value);
                    }
                }
                else
                {
                    XmlElement xe = xmlDoc.CreateElement(element);
                    if (attribute.Equals(""))
                        xe.InnerText = value;
                    else
                        xe.SetAttribute(attribute, value);
                    xn.AppendChild(xe);
                }
                //this.Save();
            }
            catch { }
        }
        #endregion

        #region 修改数据
        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="attribute">属性名，非空时修改该节点属性值，否则修改节点值</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.Insert(path, "/Node", "", "Value")
         * XmlHelper.Insert(path, "/Node", "Attribute", "Value")
         ************************************************/
        public void Update(string node, string attribute, string value, bool save)
        {
            try
            {
                XmlNode xn = xmlDoc.SelectSingleNode(node);
                if (xn == null)
                {
                    string[] arr = node.Split('/');
                    string str = string.Empty;
                    for (int i = 0; i < arr.Length - 1; ++i)
                    {
                        str += "/" + arr[i];
                    }
                    Regex rx = new Regex(@"\[.*\]");
                    string el = rx.Replace(arr[arr.Length - 1], "");
                    Insert(str, el, attribute, value);
                }
                else
                {
                    XmlElement xe = (XmlElement)xn;
                    if (attribute.Equals(""))
                        xe.InnerText = value;
                    else
                        xe.SetAttribute(attribute, value);
                }
                if (save) this.Save();
            }
            catch { }
        }
        public void Update(string node, string attribute, string value)
        {
            Update(node, attribute, value, false);
        }
        #endregion

        public void SetAttribute(string node,string name, string value)
        {
            XmlNode xn = xmlDoc.SelectSingleNode(node);
            if (xn != null)
            {
                XmlAttribute atb = xmlDoc.CreateAttribute(name);
                atb.InnerXml = value;
                xn.Attributes.Append(atb);
            }
        }

        #region 删除数据
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="attribute">属性名，非空时删除该节点属性值，否则删除节点值</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.Delete(path, "/Node", "")
         * XmlHelper.Delete(path, "/Node", "Attribute")
         ************************************************/
        public void Delete(string node, string attribute)
        {
            try
            {
                XmlNode xn = xmlDoc.SelectSingleNode(node);
                XmlElement xe = (XmlElement)xn;
                if (attribute.Equals(""))
                    xn.ParentNode.RemoveChild(xn);
                else
                    xe.RemoveAttribute(attribute);
                this.Save();
            }
            catch { }
        }
        public void DeleteChild(string node)
        {
            try
            {
                XmlNode xn = xmlDoc.SelectSingleNode(node);
                xn.RemoveAll();
            }
            catch { }
        }
        #endregion

        #region IDisposable成员
        public void Dispose()
        {
            Dispose(true);
            //GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                lock (this)
                {
                    if (disposing)
                    {
                        // Release managed resource
                        xmlDoc = null;
                        xmlFilePath = string.Empty;
                        xmlCacheKey = string.Empty;
                    }
                    // Release unmanaged resource
                    m_disposed = true;
                }
            }
        }
        ~XmlHelper()
        {
            Dispose(false);
        }
        private bool m_disposed;
        #endregion
    }
}
